package com.zy.activity.product;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import zy.dto.base.emp.EmpLoginDto;
import zy.dto.base.product.ProductCartDto;
import zy.entity.sell.cart.T_Sell_CartList;
import zy.entity.vip.member.T_Vip_Member;
import zy.entity.vip.trylist.T_Vip_TryList;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.StringUtil;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.alibaba.fastjson.JSON;
import com.zy.R;
import com.zy.activity.BaseActivity;
import com.zy.adapter.product.ProductAdapter;
import com.zy.api.base.ProductAPI;
import com.zy.api.sell.CartAPI;
import com.zy.api.sell.DayAPI;
import com.zy.api.stock.StockAPI;
import com.zy.api.vip.TryListAPI;
import com.zy.util.ActivityUtil;
import com.zy.util.CacheVipMemberUtil;
import com.zy.util.CommonParam;
import com.zy.util.Constants;
import com.zy.view.view.AutoListView;
import com.zy.view.view.AutoListView.OnLoadListener;
import com.zy.view.zxing.CaptureActivity;

public class ProductActivity extends BaseActivity implements OnLoadListener,OnClickListener{
	private TextView txt_title,tv_barcode;
	private EditText txt_search;
	private Button btn_search;
	private ImageView img_back;
	private Handler handler;
	private int pageindex = 1;
	private AutoListView autoListView;
	private ProductAdapter productAdapter;
	private ProductAPI productAPI;
	private StockAPI stockAPI;
	private CartAPI cartAPI;
	private TryListAPI tryListAPI;
	private DayAPI dayAPI;
	private List<ProductCartDto> productCartDtos = new ArrayList<ProductCartDto>();
	public static final int STATE_LOAD_STOCK = 2;
	private int currentPosition = -1;
	private T_Vip_Member member;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_product);
		initView();
		initListener();
		initHandle();
		String barcode = getIntent().getStringExtra("barcode");
		if(StringUtil.isNotEmpty(barcode)){
			Map<String, Object> paramMap = buildBaseParam();
			paramMap.put("barcode", barcode);
			productAPI.loadByBarcode(paramMap, handler, R.id.tv_barcode);
		}else {
			loadData();
		}
	}
	private void initView(){
		member = CacheVipMemberUtil.getMember();
		progress = new ProgressDialog(this);
		productAPI = new ProductAPI(this);
		stockAPI = new StockAPI(this);
		cartAPI = new CartAPI(this);
		tryListAPI = new TryListAPI(this);
		dayAPI = new DayAPI(this);
		txt_search = (EditText)findViewById(R.id.txt_search);
		txt_title = (TextView)findViewById(R.id.txt_title);
		txt_title.setText(getIntent().getStringExtra(Constants.TITLE));
		tv_barcode = (TextView)findViewById(R.id.tv_barcode);
		tv_barcode.setTypeface(iconfont);
		btn_search = (Button)findViewById(R.id.btn_search);
		img_back = (ImageView) findViewById(R.id.img_back);
		img_back.setVisibility(View.VISIBLE);
		autoListView = (AutoListView)findViewById(R.id.lv_data);
	}
	private void initListener(){
		img_back.setOnClickListener(this);
		tv_barcode.setOnClickListener(this);
		btn_search.setOnClickListener(this);
		productAdapter = new ProductAdapter(this, productCartDtos, member);
		autoListView.setOnLoadListener(this);
		autoListView.setAdapter(productAdapter);
		autoListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (position == (autoListView.getCount() - 1))
					return;
//				Bundle bundle = new Bundle();
//				bundle.putString(Constants.TITLE, "库存明细");
//				bundle.putString("pd_code", stockList.get(position).getSd_pd_code());
//				ActivityUtil.start_Activity(StockActivity.this, StockInfoActivity.class, bundle);
			}
		});
	}
	@SuppressLint("HandlerLeak")
	private void initHandle(){
		handler = new Handler() {
			@SuppressWarnings("unchecked")
			public void handleMessage(Message msg) {
				if(progress != null && progress.isShowing()){
					progress.dismiss();
				}
				switch (msg.what) {
					case STATE_LOAD:{
						if(msg.obj == null){
							return;
						}
						List<ProductCartDto> result = (List<ProductCartDto>) msg.obj;
						autoListView.onLoadComplete();
						productCartDtos.addAll(result);
						if (productCartDtos.size() > 0) {
							autoListView.setResultSize(result.size(), productCartDtos.size());
			                pageindex = productCartDtos.size()/CommonParam.pagesize+1;
			                productAdapter.notifyDataSetChanged();
						}else {
							autoListView.setResultSize(result.size(), productCartDtos.size());
						}
		                break;
					}
					case R.id.tv_barcode://条码扫描
						if(msg.obj == null){
							return;
						}
						ProductCartDto resultDto = (ProductCartDto)msg.obj;
						autoListView.onLoadComplete();
						productCartDtos.add(resultDto);
						autoListView.setResultSize(1, productCartDtos.size());
						productAdapter.notifyDataSetChanged();
						break;
					case STATE_LOAD_STOCK:
						if(msg.obj == null){
							return;
						}
						Map<String,Object> result = (Map<String,Object>) msg.obj;
						productCartDtos.get(currentPosition).setStockMap(result);
						productAdapter.notifyDataSetChanged();
						break;
					case STATE_SAVE:
						ActivityUtil.showShortToast(ProductActivity.this, "添加成功");
						setResult(RESULT_OK);
						break;
					case STATE_UPDATE:
						ActivityUtil.showShortToast(ProductActivity.this, "试穿成功");
						break;
					case STATE_ERROR:
						String message = null;
						if(msg.obj != null){
							message = msg.obj.toString();
						}
						ActivityUtil.showShortToast(ProductActivity.this, message);
						break;
				}
				super.handleMessage(msg);
			}
		};
	}
	private void flush(){
		pageindex = 1;
		productCartDtos.clear();
		productAdapter.notifyDataSetChanged();
	}

	private void loadData(){
		Map<String, Object> paramMap = buildBaseParam();
		paramMap.put(CommonUtil.PAGEINDEX, pageindex);
		paramMap.put(CommonUtil.PAGESIZE, CommonUtil.PAGE_SIZE);
		paramMap.put("searchContent", txt_search.getText().toString());
		productAPI.list(paramMap, handler, STATE_LOAD);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_back:
			ActivityUtil.finish(ProductActivity.this);
			break;
		case R.id.btn_search:
			flush();
			loadData();
			break;
		case R.id.tv_barcode:
			Intent intent = new Intent(ProductActivity.this, CaptureActivity.class);
			startActivityForResult(intent, REQUEST_CODE_SCANNER);
			break;
		default:
			break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if(requestCode == REQUEST_CODE_SCANNER){//扫一扫
				String code = data.getStringExtra("code");
				Map<String, Object> paramMap = buildBaseParam();
				paramMap.put("barcode", code);
				flush();
				productAPI.loadByBarcode(paramMap, handler, R.id.tv_barcode);
			}
		}
	}
	
	@Override
	public void onLoad() {
		loadData();
	}

	public void loadStockData(int position){
		currentPosition = position;
		Map<String, Object> params = buildBaseParam();
		params.put("pd_code", productCartDtos.get(position).getPd_code());
		stockAPI.queryStock(params, handler, STATE_LOAD_STOCK);
	}
	public void saveCartList(int position,String cr_code,String sz_code,String br_code){
		currentPosition = position;
		EmpLoginDto user = getUser();
		ProductCartDto productCartDto = productCartDtos.get(position);
		T_Sell_CartList cartList = new T_Sell_CartList();
		
		cartList.setScl_sysdate(DateUtil.getCurrentTime());
		cartList.setScl_pd_code(productCartDto.getPd_code());
		cartList.setScl_cr_code(StringUtil.trimString(cr_code));
		cartList.setScl_sz_code(StringUtil.trimString(sz_code));
		cartList.setScl_br_code(StringUtil.trimString(br_code));
		cartList.setScl_sub_code(cartList.getScl_pd_code()+cartList.getScl_cr_code()+cartList.getScl_sz_code()+cartList.getScl_br_code());
		cartList.setScl_amount(productCartDto.getAmount());
		cartList.setScl_sell_price(productCartDto.getPd_sell_price());
		cartList.setScl_state(0);
		if(member != null){
			cartList.setScl_vm_code(member.getVm_code());
		}else {
			cartList.setScl_vm_code("");
		}
		cartList.setScl_em_code(user.getEm_code());
		cartList.setScl_shop_code(user.getEm_shop_code());
		cartList.setCompanyid(user.getCompanyid());
		progress.show();
		Map<String, Object> params = buildBaseParam();
		params.put("cartList", JSON.toJSONString(cartList));
		cartAPI.saveCartList(params, handler, STATE_SAVE);
	}
	
	public void saveTryList(int position,String cr_code,String sz_code,String br_code){
		currentPosition = position;
		EmpLoginDto user = getUser();
		String tryState = CacheVipMemberUtil.getTryState();
		if(!"1".equals(tryState)){//未试穿、增加店铺和导购试穿次数
			CacheVipMemberUtil.putTryState("1");
			Map<String, Object> params = buildBaseParam();
			params.put("em_code", user.getEm_code());
			dayAPI.doTry(params, handler, -1);
		}
		ProductCartDto productCartDto = productCartDtos.get(position);
		T_Vip_TryList tryList = new T_Vip_TryList();
		tryList.setTr_sysdate(DateUtil.getCurrentTime());
		tryList.setTr_pd_code(productCartDto.getPd_code());
		tryList.setTr_cr_code(StringUtil.trimString(cr_code));
		tryList.setTr_sz_code(StringUtil.trimString(sz_code));
		tryList.setTr_br_code(StringUtil.trimString(br_code));
		tryList.setTr_sub_code(tryList.getTr_pd_code()+tryList.getTr_cr_code()+tryList.getTr_sz_code()+tryList.getTr_br_code());
		tryList.setTr_sell_price(productCartDto.getPd_sell_price());
		if(member != null){
			tryList.setTr_vm_code(member.getVm_code());
		}else {
			tryList.setTr_vm_code("");
		}
		tryList.setTr_em_code(user.getEm_code());
		tryList.setTr_shop_code(user.getEm_shop_code());
		tryList.setCompanyid(user.getCompanyid());
		progress.show();
		Map<String, Object> params = buildBaseParam();
		params.put("tryList", JSON.toJSONString(tryList));
		tryListAPI.saveTryList(params, handler, STATE_UPDATE);
	}
}
